#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h> /* 使用sockaddr_in */
#include <strings.h>
#include <arpa/inet.h>
#include <cstring>
#include "mutex"
#include "Log.hpp"

// 调用方式 ./udpclient server_ip server_port
int main(int argc, char *argv[])
{
    if(argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " server_ip server_port" << std::endl;
        return -1;
    }

    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    /* 1. 创建socket */
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        std::cerr << "socket error" << std::endl;
        return -2;
    }

    /* 
        2. 客户端需要bindIP号, 端口号，但是客户端不需要显示的bind，让系统自动分配对应的端口号
        首次发送消息，OS会自动给client进行bind，OS知道IP，端口号采用随机端口号的方式
        采用随机端口是为了防止多个client访问服务器时端口号重复
    */
    struct sockaddr_in server;
    /* 置为0 */
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET; /* IPv4 */
    server.sin_port = htons(server_port);
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());

    while(true)
    {
        std::string input;
        std::cout << "Please Enter# ";
        std::getline(std::cin, input);

        /* 1. 向服务器发送消息 */
        int n = sendto(sockfd, input.c_str(), input.size(), 0, (const struct sockaddr*)&server, sizeof(server));
        (void)n;

        /* 2. 接收服务器发送的消息 */
        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int m = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&peer, &len);
        if(m > 0)
        {
            buffer[m] = 0;
            std::cout << buffer << std::endl;
        }
    }
    return 0;
}